package first.codeTop.meituan;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName Leetcode102
 * @description:
 * @author: 荣燊
 * @create: 2021-08-02 21:36
 **/
public class Leetcode102 {
    // 二叉树的层序遍历
    public static void main(String[] args) {

    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        if (root == null) {
            return result;
        }
        deque.addFirst(root);

        // 开始遍历
        while (!deque.isEmpty()) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int i=deque.size(); i>0; i--) {
                TreeNode treeNode = deque.pollLast();
                list.add(treeNode.val);
                if (treeNode.left != null) {
                    deque.addFirst(treeNode.left);
                }
                if (treeNode.right != null) {
                    deque.addFirst(treeNode.right);
                }
            }
            result.add(list);
        }
        return result;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
